package com.devplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.devplatform.pojo.points.*;
import com.devplatform.pojo.user.User;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.pojo.vo.PointsDetailVO;
import com.devplatform.service.impl.UserService;
import com.devplatform.service.points.*;
import com.devplatform.util.UserContextHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/points")
public class pointsController {
    private final UserPointsService userPointsService;
    private final PointsDetailService pointsDetailService;
    private final UserLevelService userLevelService;
    private final PointsMallService pointsMallService;
    private final OrderService orderService;
    private final PointsReasonService pointsReasonService;
    private final UserService userService;

    // 获取用户签到状态
    @GetMapping("/user/checkIn/status")
    public DataVo<Map<String, Object>> getCheckInStatus() {
        Long userId = UserContextHolder.getUserId();
        Map<String, Object> status = userPointsService.getCheckInStatus(userId);
        return DataVo.ok(status);
    }
    //用户签到
    @PostMapping("/checkIn")
    public DataVo checkin() {
        try {
            Long userId = UserContextHolder.getUserId();
            Map<String, Object> checkInData = userPointsService.userCheckIn(userId);
            return DataVo.ok(checkInData);
        } catch (RuntimeException e) {
            return DataVo.error(e.getMessage());
        }
    }

    // 文章相关积分发放（发布/点赞/回复）
    @PostMapping("/article/reward")
    public DataVo<String> rewardArticlePoints(@RequestBody ArticleReasonDto dto) {
        Long userId = UserContextHolder.getUserId();
        pointsDetailService.ArticlePoints(userId, dto.getReasonCode());
        return DataVo.ok("积分发放成功");
    }

    // 积分提升文章热度
    @PostMapping("/article/increaseHot")
    public DataVo<String> increaseArticleHot(@RequestBody HotValueDto dto) {
        Long userId = UserContextHolder.getUserId();
        userPointsService.exchangePointsForHot(userId, dto.getArticleId(), dto.getHotValue());
        return DataVo.ok("热度提升成功");
    }

    //  获取用户当前积分信息
    @GetMapping("/info")
    public DataVo<Map<String, Object>> getUserPointsInfo() {
        Long userId = UserContextHolder.getUserId();
        Map<String, Object> pointsInfo = userPointsService.getUserPointsInfo(userId);
        return DataVo.ok(pointsInfo);
    }

    //获取本月积分消息
    @GetMapping("/month-summary")
    public DataVo<MonthPointsSummaryDTO> getMonthPointsSummary() {
        Long userId = UserContextHolder.getUserId();
        MonthPointsSummaryDTO summary = userPointsService.getMonthPointsSummary(userId);
        return DataVo.ok(summary);
    }


    // 获取积分明细（分页）
    @GetMapping("/detail")
    public DataVo<Page<PointsDetailVO>> getPointsDetail(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String reasonCode) {

        Long userId = UserContextHolder.getUserId();
        if (userId == null) {
            return DataVo.error(401, "未登录或会话已过期");
        }

        Page<PointsDetail> detailPage = pointsDetailService.getDetail(userId, pageNum, pageSize, reasonCode);


        Page<PointsDetailVO> voPage = new Page<>(pageNum, pageSize);
        voPage.setTotal(detailPage.getTotal()); // 设置总条数


        List<PointsDetailVO> voList = new ArrayList<>();
        detailPage.getRecords().forEach(detail -> {
            PointsDetailVO vo = new PointsDetailVO();
            vo.setDetailId(detail.getDetailId());
            vo.setUserId(detail.getUserId());
            vo.setPointsChange(detail.getPointsChange());
            vo.setReasonCode(detail.getReasonCode());

            // 防止 reasonCode 为 null 或找不到对应原因
            if (detail.getReasonCode() != null) {
                PointsReason reason = pointsReasonService.getByReasonCode(detail.getReasonCode());
                vo.setReasonName(reason != null ? reason.getReasonName() : "未知原因");
            } else {
                vo.setReasonName("未知原因");
            }

            vo.setCreateTime(detail.getCreateTime());
            voList.add(vo); // 向可修改列表中添加 VO
        });


        voPage.setRecords(voList);

        return DataVo.ok(voPage);
    }

    //  查询用户等级及升级进度

    @GetMapping("/level/info")
    public DataVo<Map<String, Object>> getLevelInfo() {
        Long userId = UserContextHolder.getUserId();
        return DataVo.ok(userLevelService.getUserLevel(userId));
    }

    //查看所有等级
    @GetMapping("/level/privileges")
    public DataVo<List<UserLevel>> getLevelPrivileges() {
        return DataVo.ok(userLevelService.list());
    }

    // 用户端：查询可兑换商品列表（过滤等级限制和库存）

    @GetMapping("/mall/goods")
    public DataVo<Page<PointsMall>> getAvailableGoods(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = UserContextHolder.getUserId();
        // 查询用户等级，过滤掉等级不够的商品
        User userLevel = userService.getById(userId);
        Page<PointsMall> goods = pointsMallService.getPointsMall(userLevel.getLevel(), pageNum, pageSize);

        return DataVo.ok(goods);
    }


    // 用户端：兑换商品（校验积分、等级、库存）

    @PostMapping("/mall/exchange")
    public DataVo exchangeGoods(@RequestBody GoodsIdDto dto) {
        try {
            Long userId = UserContextHolder.getUserId();
            Order order = orderService.createOrder(userId, dto.getGoodsId());
            return DataVo.ok("商品兑换成功，订单已创建" + order.getOrderId());
        } catch (RuntimeException e) {
            return DataVo.error(e.getMessage());
        }
    }


    // 用户端：查询兑换订单列表

    @GetMapping("/mall/orders")
    public DataVo<Page<OrderVo>> getExchangeOrders(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = UserContextHolder.getUserId();
        Page<OrderVo> page = new Page<>(pageNum, pageSize);
        Page<OrderVo> orderPage = orderService.getOrderWithGoodsName(page, userId);
        return DataVo.ok(orderPage);
    }


    // 运营端：添加商品

    @PostMapping("/admin/mall/goods")
    public DataVo addGoods(@RequestBody PointsMall goods) {
        try {
            pointsMallService.save(goods);
            return DataVo.ok("商品添加成功" + goods.getGoodsId());
        } catch (RuntimeException e) {
            return DataVo.error(e.getMessage());
        }
    }


    // 运营端：编辑商品信息

    @PutMapping("/admin/mall/goods")
    public DataVo updateGoods(@RequestBody PointsMall goods) {
        try {
            pointsMallService.updateById(goods);
            return DataVo.ok("商品更新成功");
        } catch (RuntimeException e) {
            return DataVo.error(e.getMessage());
        }
    }

    // 运营端：下架商品（更新状态）

    @PostMapping("/admin/mall/goods/off")
    public DataVo offlineGoods(@RequestBody GoodsIdDto dto) {
        PointsMall goods = new PointsMall();
        goods.setGoodsId(dto.getGoodsId());
        goods.setStatus(0); // 0=下架
        pointsMallService.updateById(goods);
        return DataVo.ok("商品已下架");
    }

    // 上架商品接口
    @PostMapping("/admin/mall/goods/on")
    public DataVo onGoods(@RequestBody GoodsIdDto dto) {
        try {
            pointsMallService.onGoods(dto.getGoodsId());
            return DataVo.ok("商品上架成功");
        } catch (RuntimeException e) {
            return DataVo.error(e.getMessage());
        }
    }

    // 运营端：搜索商品（支持按名称模糊查询）
    @GetMapping("/admin/mall/goods/search")
    public DataVo<Page<PointsMall>> searchGoods(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize,
            @RequestParam(required = false) String goodsName) {  // 商品名称搜索关键词

        Page<PointsMall> page = new Page<>(pageNum, pageSize);
        QueryWrapper<PointsMall> queryWrapper = new QueryWrapper<>();

        // 如果有搜索关键词，添加模糊查询条件
        if (goodsName != null && !goodsName.isEmpty()) {
            queryWrapper.like("goods_name", goodsName);
        }

        // 执行分页查询
        Page<PointsMall> goodsPage = pointsMallService.page(page, queryWrapper);
        return DataVo.ok(goodsPage);
    }
    // 运营端：查询所有商品（含下架）

    @GetMapping("/admin/mall/goods")
    public DataVo<Page<PointsMall>> getAllGoods(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        Page<PointsMall> page = new Page<>(pageNum, pageSize);
        return DataVo.ok(pointsMallService.page(page));
    }

}
